var balancePrice, machineModel, machineSerialNo, outTimeStart, outTimeEnd, buyer, status = -99,
  custPay = -99,
  watchBord = 0;
var serverUrl = getPath();

function getQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var r = decodeURI(window.location.search).substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}
$(function () {
  if (getQueryString("watchBord") != null) { //如果是看板查询功能去除
    watchBord = 1;
    $("#status").parent().parent().parent().hide();
  }
  var isBoard = getQueryString("board");
  if (isBoard === "false") {
    $(".title").remove();
  }
  queryClass();
  page.bind();
  if (isBoard !== "false") {
    getUserName();
  }
});
var page = { //页面总变量
  _this_selectDialog: "",
  _this_selectDialog_val: "",
  bind: function () {
    $("#search").unbind("click");
    $("#search").bind("click.my", function () {
      machineModel = $("#machineModel").val();
      machineSerialNo = $("#machineSerialNo").val();
      outTimeStart = $("#outTimeStart").val();
      outTimeEnd = $("#outTimeEnd").val();
      buyer = $("#buyer").val();
      status = $("#status").val();
      custPay = $("#custPay").val();
      balancePrice = $("#balancePrice").val();
      queryClass();
    })
    $(window.parent.document).find("span[data-href='workorderlist.html']").parent().unbind('click.my');
    $(window.parent.document).find("span[data-href='workorderlist.html']").parent().bind('click.my', function () {
      reloadData();
    })
    $("#delete_order_sure").unbind("click.my");
    $("#delete_order_sure").bind("click.my", function () {
      page.deletesure();
    })
    //添加设备 出现dialog
    $("#addMachine").unbind("click");
    $("#addMachine").bind("click", function () {
      page.addMachine();
    })
    //保存设备
    $("#addMachineSubmit").unbind("click");
    $("#addMachineSubmit").bind("click", function () {
      $("#form-addMachine").ajaxSubmit(function () {
        alert("保存成功");
        $("#addMachine-modal-demo").find(".close").click();
        reloadData();
      });
    })
    //更新设备
    $("#updateMachineSubmit").unbind("click");
    $("#updateMachineSubmit").bind("click", function () {
      $("#form-updateMachine").ajaxSubmit(function () {
        alert("更新成功");
        $("#updateMachine-modal-demo").find(".close").click();
        reloadData();
      });
    });
    //主管 和 技工绑定事件
    $("[name='serviceManager']").unbind("click");
    $("[name='serviceManager']").bind("click", function () {
      page._this_selectDialog = this;
      page.selectDialog();
    })
    $("[name='serviceWorker']").unbind("click");
    $("[name='serviceWorker']").bind("click", function () {
      page._this_selectDialog = this;
      page.selectDialog();
    });
    //保存结算价格
    $("#updateBalancePrice").unbind("click");
    $("#updateBalancePrice").bind("click", function () {
      $("#updateBalancePrice").hide();
      $("#form-balancePrice").ajaxSubmit(function () {
        alert("保存成功");
        $("#updateBalancePrice").show();
        reloadData();
      });
    })
  //上下表头内容同步滚动
	$(".dataTables_scrollHead").css("overflow","auto")
	$(".dataTables_scrollHead").append("<style>	.dataTables_scrollHead::-webkit-scrollbar {display:none}</style>");
	$(".dataTables_scrollBody").scroll(function(event){
		$(".dataTables_scrollHead").scrollLeft($(this).scrollLeft()) ;
	});
  },
  //选择人员
  selectDialog: function () {
    $('div#easyui_dialog_index').dialog({
      modal: true,
      title: '人员设备',
      width: "500",
      height: "400",
      closed: false,
      border: true,
      cache: false,
      content: "<iframe frameborder='0' scrolling='no' style='width:99%;height:97%;' src='userSelectDialog.html'></iframe>",
      onClose: function () {
        $("div#easyui_dialog_index").dialog('destroy');
        $("body").append("<div id='easyui_dialog_index'></div>");
      },
      buttons: [{
        text: '确定',
        iconCls: 'icon-ok',
        handler: function () {
          var rows = $("[src='userSelectDialog.html']")[0].contentWindow.getSelectRows();
          if (rows.length < 1) {
            alert("请设置人员");
            return;
          }
          var str = "";
          for (i = 0; i < rows.length; i++) {
            str += rows[i].text + ","
          }
          str = str.substring(0, str.length - 1);
          $(page._this_selectDialog).val(str);
          $("div#easyui_dialog_index").dialog('destroy');
          $("body").append("<div id='easyui_dialog_index'></div>");
        }
      }]
    });
    //赋值
    page._this_selectDialog_val = $(page._this_selectDialog).val();
  },
  //添加设备
  addMachine: function () {
    $("#addMachine-modal-demo").modal("show");
  },
  //更新设备
  updateMachine: function (self) {
    $("#updateMachine-modal-demo").modal("show");
    var table = $('#attendanceClassTable').DataTable();
    var data;
    setTimeout(function () {
      data = table.row('.selected').data();
      console.info(data);
      $("#form-updateMachine").find("[name='id']").val(data.id);
      $("#form-updateMachine").find("[name='machineModel']").val(data.machineModel);
      $("#form-updateMachine").find("[name='machineSerialNo']").val(data.machineSerialNo);
      $("#form-updateMachine").find("[name='custName']").val(data.custName);
      $("#form-updateMachine").find("[name='custPhone']").val(data.custPhone);
      $("#form-updateMachine").find("[name='custBrokenPart']").val(data.custBrokenPart);
      $("#form-updateMachine").find("[name='custBrokenDescription']").val(data.custBrokenDescription);
      $("#form-updateMachine").find("[name='custPhoto']").val();
      $("#mycustphoto").empty();
      var pics = data.custPhoto.split(",");
      for (i = 0; i < pics.length; i++) {
        $("#mycustphoto").append("<a title='点击查看大图'  target='_blank' href='" + pics[i] + "'><img style='width:100px;height:100px' src='" +
          pics[i] + "'/></a>");
      }
      $("#form-updateMachine").find("[name='workName']").val(data.workName);
      $("#form-updateMachine").find("[name='workManagerName']").val(data.workManagerName);
      $("#form-updateMachine").find("[name='workBrokenPart']").val(data.workBrokenPart);
      $("#form-updateMachine").find("[name='workBrokenDescription']").val(data.workBrokenDescription);
      $("#form-updateMachine").find("[name='workBrokenSolveWay']").val(data.workBrokenSolveWay);
      if (isNaN(data.custEvaluation)) {
        $("#form-updateMachine").find("[name='custEvaluation']").val(data.custEvaluation);
      } else {
        $("#form-updateMachine").find("[name='custEvaluation']").val(data.custEvaluation + "星评价");
        if (data.custEvaluation == null) {
          $("#form-updateMachine").find("[name='custEvaluation']").val(data.custEvaluation);
        }
      }
      $("#form-updateMachine").find("[name='custOpinion']").val(data.custOpinion);
      $("#form-updateMachine").find("[name='remark']").val("");
      if (data.remark != null && data.remark.length > 0) {
        var remark = JSON.parse(data.remark);
        var remarkStr = "";
        for (i = remark.length - 1; i > -1; i--) {
          remarkStr += timestampToTime(remark[i].time) + " " + remark[i].remark + "\r\n";
        }
        $("#form-updateMachine").find("[name='remark']").val(remarkStr);
      }

    }, 200)
  },
  //二维码
  qrcode: function (id) {
    $("#qrcode-modal-demo").modal("show");
    $('#qrcodeDIV').empty();
    $('#qrcodeDIV').qrcode({ //生成二维码
      render: "canvas",
      text: serverUrl + "/workOrder/sqr?id=" + id,
      render: "canvas", //设置渲染方式
      width: $("#qrcodeDIV").width(), //设置宽度
      height: $("#qrcodeDIV").height(), //设置高度
      typeNumber: -1, //计算模式
      //correctLevel    : QRErrorCorrectLevel.H,//纠错等级
      background: "#ffffff", //背景颜色
      //src: '../../../images/zfb_logo.jpg',
      foreground: "#000000" //前景颜色
    });
  },
  //核算价格
  checkPrice: function () {
    $("#settlementPrice-modal-demo").modal("show");
    var table = $('#attendanceClassTable').DataTable();
    var data;
    setTimeout(function () {
      data = table.row('.selected').data();
      $.ajax({
        type: "POST",
        url: "workOrder/getWorkRepairPriceList",
        dataType: "json",
        data: {
          "type": 1,
          "status": 1,
          "linkId": data.id
        },
        success: function (data) {
          console.info(data);
          $("#settlementPrice-modal-demo").find(".modal-body").empty();
          if (data.data.length != 0) {
            var str = `<table class="table table-border table-bordered">
						  <thead class="text-c">
						    <tr>
						      <th>物料名称</th>
						      <th>单价(元)</th>
						      <th>数量</th>
						      <th>金额</th>
						      <th>实际收款(元)</th>
						    </tr>
						  </thead> <tbody>`;
            for (var i = 0; i < data.data.length; i++) {
              str += `<tr>
							<td><input hidden type="text" name='id' value=` + data.data[i].id + `>` + data.data[i].materialName + `</td>
							<td>` + data.data[i].price + `</td>
							<td>` + data.data[i].total + `</td>
							<td>` + data.data[i].total * data.data[i].price + `</td>
							<td><input class='input-text' type="text" name='balancePrice' value=` + data.data[i].balancePrice + `>` + `</td>
							</tr>`;
            }
            $("#settlementPrice-modal-demo").find(".modal-body").append(str);
          } else {
            $("#settlementPrice-modal-demo").find(".modal-body").append("无维修价目");
          }
          $("[name='balancePrice']").bind("blur", function () {
            $(this).val($(this).val().replace(/[^\d.]/g, "").replace(/\.{2,}/g, "."))
          })

        }
      });
    });
  }
}

function reloadData() {
  var table = $('#attendanceClassTable').DataTable();
  table.draw(false);
}
//查询
function queryClass() {
  //避免多次绑定
  var table = $('#attendanceClassTable').DataTable();
  $('#attendanceClassTable tbody').unbind("click");
  ajaxUtil.dataTablesAjax("attendanceClassTable", 10, "workOrder/getApplyList", {
      "machineModel": machineModel,
      "machineSerialNo": machineSerialNo,
      "outTimeStart": outTimeStart,
      "outTimeEnd": outTimeEnd,
      "buyer": buyer,
      "status": status,
      "custPay": custPay,
      "balancePrice": balancePrice,
      "watchBord": watchBord
    },
    [{
        "data": "machineModel"
      },
      {
        "data": "machineSerialNo"
      },
      {
        "data": "custCompany"
      },
      {
        "data": "custName"
      },
      {
        "data": "custPhone"
      },
      
      {
        "data": "workBrokenDescription"
      },
      {
          "data": "errorCode",
          render: function (data, type, row) {
        	  if(data.length>0){
        		  return row.errorMsg + "("+data+")";
        	  }
        	  return "";
          }
      },
      {
        "data": "custEvaluation",
        render: function (data, type, row) {
          if (data && data.length > 0) {
            if (isNaN(data)) {
              return data;
            } else {
              return data + "星评价";
            }
          }
          return "";
        }
      },
      {
    	  "data": "workName",
      },
      {
        "data": "custPay",
        render: function (data, type, row) {
          console.info(row.balancePrice);
          if (row.status <= 1) {
            return "";
          }
          var str = "";
          if (data == 1) {
            str = "收费"
          } else {
            str = "不收费"
          }
          if (row.balancePrice == 0) {
            str = "不收费已结算"
          }
          if (data == 1 && row.balancePrice == null) {
            str += "待结算";
          }
          if (data != 1 && row.balancePrice == null) {
            str += "已结算";
          }
          if (data == 1 && row.balancePrice != null && row.balancePrice != 0) {
            str += "已结算";
          }

          return str;
        }
      },
      {
        "data": "status",
        render: function (data, type, row) {
          if (data == -2) {
            return "已退回";
          }
          if (data == -1) {
            return "待申请";
          }
          if (data == 0) {
            return "<p style='color:red'>指派中</p>";
          }
          if (data == 1) {
            return "<p style='color:#FFA500'>处理中</>";
          }
          if (data == 2) {
            return "<p style='color:green'>待评价</p> ";
          }
          if (data == 3) {
            return "<p style='color:green'>处理完毕</p>";
          }
        }
      },
      {
        "data": "createTime",
         render: function (data, type, row) {
        	 return "<p title="+row.createTime+">"+data.slice(5,-3)+"</p>";
         }
        	
      },
      {
          "data": "assignTime",
          render: function (data, type, row) {
            if(data!=null){
            	return takeUpTime(row.createTime,data)
            }
            return "";
          }
      },
      {
          "data": "workCompleteTime",
          render: function (data, type, row) {
        	  if(data!=null&&row.assignTime!=null){
              	return takeUpTime(row.assignTime,data)
              }
        	  return "";
          }
      },
      {
    	  "data": "workCompleteLocation",
      },
      {
        "data": "id",
        render: function (data, type, row) {
          if (watchBord == 1) {
            return '<input class="btn btn-link" type="button" value="查看详情"  onclick="page.updateMachine()">';
          } else {
            return '<input class="btn btn-link" type="button" value="查看详情"  onclick="page.updateMachine()"><input class="btn btn-link" type="button" value="结算价格"  onclick="page.checkPrice()">';
          }

        }
      }
    ]);
  $('#attendanceClassTable').on('init.dt', function (e, settings) {
      layer.msg("查询完成", {
        icon: 1
      });
      page.bind();
      //避免不对齐
      setTimeout(function () {
        var table = $.fn.dataTable.fnTables(true);
        if (table.length > 0) {
          $(table).dataTable().fnAdjustColumnSizing();
        }
      }, 1000)
    })
    .on('xhr.dt', function (e, settings, json, xhr) {
      if (xhr !== undefined) {
        if (xhr.status == 200) {
          //自己的代码
          var json = xhr.responseText;
          var jsonString = JSON.parse(json);
          if (jsonString.result === false) {
            layAlert(jsonString.info);
            if (jsonString.info.indexOf("未登陆") > -1) {
              setTimeout(function () {
                window.location.href = "login.html?redirectUrlForLogin=" + window.location.href;
              }, 2000)
            }
            return;
          }
        }
      }
    });
  $('#attendanceClassTable tbody').on('click', 'tr', function () {
    $('#attendanceClassTable tbody').find("tr").removeClass('selected');
    $(this).addClass('selected');
  });
}
/**
 * loadFilter: function (data, parent) {
 *  var opt = $(this).data().treegrid.options;
 *  return treeFilter(data, opt);
 * }
 * 
 * idField : 'id'
 * treeField : 'text'  //必须指定
 * parentField : 'pid' //必须指定
 * @param data
 * @param opt
 * @returns
 */
function treeFilter(data, opt) {
  var idField,
    treeField,
    parentField;
  if (opt.parentField) {
    idField = opt.idField || 'id';
    treeField = opt.treeField || 'text';
    parentField = opt.parentField;

    var i,
      l,
      treeData = [],
      tmpMap = [];

    for (i = 0, l = data.length; i < l; i++) {
      tmpMap[data[i][idField]] = data[i];
    }

    for (i = 0, l = data.length; i < l; i++) {
      if (tmpMap[data[i][parentField]] && data[i][idField] != data[i][parentField]) {
        if (!tmpMap[data[i][parentField]]['children'])
          tmpMap[data[i][parentField]]['children'] = [];
        data[i]['text'] = data[i][treeField];
        tmpMap[data[i][parentField]]['children'].push(data[i]);
      } else {
        data[i]['text'] = data[i][treeField];
        treeData.push(data[i]);
      }
    }
    return treeData;
  }
  return data;
}

function getPath() {
  var strFullPath = window.document.location.href;
  var strPath = window.document.location.pathname;
  var pos = strFullPath.indexOf(strPath);
  var prePath = strFullPath.substring(0, pos);
  var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
  var basePath = prePath;
  basePath = prePath + postPath;
  return basePath;
}

function getPrePath() {
  var strFullPath = window.document.location.href;
  var strPath = window.document.location.pathname;
  var pos = strFullPath.indexOf(strPath);
  var prePath = strFullPath.substring(0, pos);
  var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
  var basePath = prePath;
  return basePath;
}
//时间戳格式化
function timestampToTime(timestamp) {
  var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var D = date.getDate() + ' ';
  var h = date.getHours() + ':';
  var m = date.getMinutes() + ':';
  var s = date.getSeconds();
  return Y + M + D + h + m + s;
}
/*
$("iframe[src='./html/createOrder/index_x.html']")[0].contentWindow.basic_index.getTempForOrder('182','SC180308000010')*/

/**
 * sse
 */
if (!!window.EventSource) {
  var source = new EventSource(serverUrl + '/sse/workOrder/addApplyWorkOrder');
  console.log(source.readyState);
  s = ' ';

  /* message event listener */
  source.addEventListener('message', function (e) {
    console.info(e.data.length > 0);
    if (e.data.length > 0) {
      $("#audio_1").remove();
      $("body").append('<audio id="audio_1" src="https://upload.shinehao.com.cn/mp3/newWorkOrder.mp3" controls autoplay hidden></audio>')
      reloadData();
    }
  });

  /* open event listener */
  source.addEventListener('open', function (e) {
    console.log("Connection is open");
  }, false);

  /* error event listener */
  source.addEventListener('error', function (e) {
    if (e.readyState == EventSource.CLOSED) {
      console.log("Connection is closed");
    } else {
      console.log("e.readyState");
    }
  }, false);
} else {
  alert("Your web browser dosen't support EventSource.");
}

/*setTimeout(function(){
	window.location.reload();
},1000*60*5)*/

function getUserName() {
  ajaxUtil.ajaxRuquestNoQuan(serverUrl + '/user/getUserName', null, function (data) {
    $("#company").text(data.company);
  });
}

setInterval(function () {
  var table = $.fn.dataTable.fnTables(true);
  if (table.length > 0) {
    $(table).dataTable().fnAdjustColumnSizing();
  }
}, 1000)

function takeUpTime(date1,date2){
	//var date1= '2015-05-01 00:00:00';  //开始时间
    //var date2 = '2015-05-01 01:01:01';    //结束时间
    var date3 = new Date(date2).getTime() - new Date(date1).getTime();   //时间差的毫秒数

    //------------------------------

    //计算出相差天数
    var days=Math.floor(date3/(24*3600*1000))

    //计算出小时数

    var leave1=date3%(24*3600*1000)    //计算天数后剩余的毫秒数
    var hours=Math.floor(leave1/(3600*1000))
    //计算相差分钟数
    var leave2=leave1%(3600*1000)        //计算小时数后剩余的毫秒数
    var minutes=Math.floor(leave2/(60*1000))
    //计算相差秒数
    var leave3=leave2%(60*1000)      //计算分钟数后剩余的毫秒数
    var seconds=Math.round(leave3/1000)
    var returnData = "";
    if(days>0){
    	returnData+=days+"天 ";
    }
    if(hours>0){
    	returnData+=hours+"小时 ";
    }
    if(minutes>0){
    	returnData+=minutes+"分钟 ";
    }
    if(seconds>0){
    	if(returnData.length==0){
    		returnData+=seconds+"秒 ";
    	}
    }
    return returnData;
}
